<template>
  <view class="cart-page">
	  <button size="mini" style="float: right;" @click="delallfn">清空购物车</button>
    <view 
      class="cart-item" 
      v-for="(item, index) in cartList" 
      :key="item.cartid"
    >
	<checkbox-group @change="(e) => handleCheckGroup(index, e)">
	  <checkbox :value="item.cartid" :checked="item.flag"></checkbox>
	</checkbox-group>
      <!-- <checkbox 
        :checked="item.flag" 
        @change="(e) => handleCheck(index, e.detail.checked)"
      ></checkbox> -->
      <image :src="item.img1" class="item-img"></image>
      <view class="item-info">
        <view class="item-name">{{ item.proname }}</view>
        <view class="price-info">
          价格：¥{{ item.originprice }} 
          <view class="count-control">
            <button size="mini" @click="decrement(index)">-</button>
            <text>{{ item.num }}</text>
            <button size="mini" @click="increment(index)">+</button>
          </view>
        </view>
      </view>
      <button class="delete-btn" @click="deleteCartItem(index)">删除</button>
    </view>
    <view class="total-info">
      <view>已选商品：{{ selectedCount }} 件</view>
      <view>总计：¥{{ totalPrice.toFixed(2) }}</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cartList: [],
      selectedCount: 0,
      totalPrice: 0
    };
  },
  onLoad() {
    this.sendfn();
  },
  methods: {
	  delallfn(){
		  const token = uni.getStorageSync('token');
		  const userid = uni.getStorageSync('userid'); 
		  uni.request({
		    url: 'http://47.94.6.186:3001/api/cart/removeall',
		    method: 'POST',
		    header: { 'token': token },
		    data: { userid },
		    success: (res) => {
		       console.log(res.data);
			    this.sendfn();
				uni.showToast({ title: '清空成功', icon: 'none' });
		    }
		  });
	  },
    sendfn() {
      const token = uni.getStorageSync('token');
      const userid = uni.getStorageSync('userid'); 
      if (!token || !userid) return uni.showToast({ title: '请先登录', icon: 'none' });
      uni.request({
        url: 'http://47.94.6.186:3001/api/cart/list',
        method: 'POST',
        header: { 'token': token },
        data: { userid },
        success: (res) => {
            this.cartList = res.data.data;
			this.calculateTotal()
        }
      });
    },
 handleCheckGroup(index, e) {
    const item = this.cartList[index];
    const isChecked = e.detail.value.includes(item.cartid);
    item.flag = isChecked; 
    this.calculateTotal(); 
    const token = uni.getStorageSync('token');
    uni.request({
      url: 'http://47.94.6.186:3001/api/cart/selectone', 
      method: 'POST',
      header: { 'token': token },
      data: { cartid: item.cartid, flag: isChecked },
      success: (res) => {
        if (res.data.code === '200') {
          uni.showToast({ title: '状态更新成功', icon: 'success' });
		  console.log(res)
        } 
      },
    });
  },
    decrement(index) {
      if (this.cartList[index].num > 1) {
        this.cartList[index].num--;
        this.calculateTotal(); 
      }
    },
    increment(index) {
      this.cartList[index].num++;
      this.calculateTotal();
    },
 calculateTotal() {
   let count = 0, price = 0;
   this.cartList.forEach(item => {
     if (item.flag) { 
       count += item.num;
       price += item.originprice * item.num;
     }
   });
   this.selectedCount = count;
   this.totalPrice = price;
 },
    deleteCartItem(index) {
      const item = this.cartList[index];
      const token = uni.getStorageSync('token');
      uni.request({
        url: 'http://47.94.6.186:3001/api/cart/remove', 
        method: 'POST',
        header: { 'token': token },
        data: { cartid: item.cartid },
        success: (res) => {
            this.cartList.splice(index, 1);
            this.calculateTotal(); 
            uni.showToast({ title: '删除成功', icon: 'none' });
        }
      });
    }
  }
}
</script>

<style scoped>
.cart-page {
  padding: 10px;
  padding-bottom: 60px; 
}
.cart-item {
  display: flex;
  align-items: center;
  margin-top:30px;
  padding: 10px;
  border-radius: 5px;
  justify-content: space-between;
}
.item-img {
  width: 80px;
  height: 80px;
  margin-right: 10px;
  border-radius: 5px;
}
.item-info {
  flex: 1;
  margin-right: 10px;
}
.price-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.count-control {
  display: flex;
  align-items: center;
}
.count-control button {
  width: 30px;
  height: 30px;
  padding: 0;
  margin: 0 5px;
}
.delete-btn {
  background: #f44336;
  color: #fff;
  font-size: 12px;
  padding: 5px 10px;
}
.total-info {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 15px;
  background:orangered;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #eee;
  padding-bottom: 60px;
  padding-right: 0%;
}
</style>